package com.example.sj12.ui.notifications;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.bumptech.glide.Glide;
import com.example.sj12.Data;
import com.example.sj12.R;
import com.example.sj12.UserDao;
import com.example.sj12.uploadLogFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class NotificationsFragment extends Fragment implements View.OnClickListener{
    private static final String TAG = "测试";
    //private static final int RESULT_OK = ;
    private boolean hasPermission = false;
    private static final int REQUEST_TAKE_PHOTO = 0;// 拍照
    private static final int REQUEST_CROP = 1;// 裁剪
    private static final int SCAN_OPEN_PHONE = 2;// 相册
    private static final int REQUEST_PERMISSION = 100;
    private Uri txUri;// 图片裁剪时返回的uri
    private File imgFile;// 拍照保存的图片文件
    private ImageView tx;
    private NotificationsViewModel notificationsViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        notificationsViewModel =
                ViewModelProviders.of(this).get(NotificationsViewModel.class);
        View root = inflater.inflate(R.layout.fragment_notifications, container, false);
        /*final TextView textView = root.findViewById(R.id.text_notifications);
        notificationsViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });*/
        //final String username1 = getActivity().getIntent().getStringExtra("username");//需要将数据传递到UserFragment中显示，
        tx=(ImageView)root.findViewById(R.id.tx);
        tx.setOnClickListener(this);
        final TextView username=root.findViewById(R.id.username);
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserDao ud = new UserDao();
                final Data get=ud.GetSUser(getActivity().getIntent().getStringExtra("username"));
                Handler mHandler = new Handler(Looper.getMainLooper()) {

                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        super.handleMessage(msg);
                        // 切换到主线程
                        //DataAdapter mAdapter = new DataAdapter((LinkedList<Data>) mData, mContext);//初始化适配器对象
                        //list.setAdapter(mAdapter);//设置适配器
                        Glide.with(getActivity())
                                .load(get.getUrl())
                                .into(tx);
                        username.setText(get.getUsername());
                        System.out.println(get.getUsername());
                    }
                };
                mHandler.sendEmptyMessage(0);
            }
        }).start();
        return root;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tx:
                checkPermissions();
                if (hasPermission) {
                    openGallery();
                }

                break;

            default:
                break;


        }
    }
    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查是否有存储和拍照权限
            if (getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    && getActivity().checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
            ) {
                hasPermission = true;
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, REQUEST_PERMISSION);
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                hasPermission = true;
            } else {
                Toast.makeText(getActivity(), "权限授予失败！", Toast.LENGTH_SHORT).show();
                hasPermission = false;
            }
        }
    }
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);//Intent打开一个Activity并从中选取一个想要的内容例如图片、用户号码等
        intent.setType("image/*");//指定类型setType
        startActivityForResult(intent, SCAN_OPEN_PHONE);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                // 拍照并进行裁剪
                case REQUEST_TAKE_PHOTO:
                    Log.e(TAG, "onActivityResult: imgUri:REQUEST_TAKE_PHOTO:" + txUri.toString());
                    cropPhoto(txUri, true);
                    break;

                // 裁剪后设置图片
                case REQUEST_CROP:
                    tx.setImageURI(txUri);
                    //Uri uri = data.getData();
                    //String img_src = uri.getPath();//选择图片的地址
                    //File compressedImage1File=new File(img_src);
                    String url="http://47.112.156.101/Uploadstx/Uploadstx";
                    new uploadLogFile(getActivity(),url,txUri.getPath(),getActivity().getIntent().getStringExtra("username"));
                    //new uploadLogFile(compressedImage1File).execute("http://47.96.249.102/savePic/savePic");//后台的接口地址
                    Log.e(TAG, "onActivityResult: imgUri:REQUEST_CROP:" + txUri.toString());
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            UserDao ud = new UserDao();
                            ud.Updatectx(getActivity().getIntent().getStringExtra("username"));
                        }
                    }).start();
                    break;
                // 打开图库获取图片并进行裁剪
                case SCAN_OPEN_PHONE:
                    Log.e(TAG, "onActivityResult: SCAN_OPEN_PHONE:" + data.getData().toString());
                    cropPhoto(data.getData(), false);
                    break;

                default:
                    break;
            }
        }
    }
    // 图片裁剪
    private void cropPhoto(Uri uri, boolean fromCapture) {
        Intent intent = new Intent("com.android.camera.action.CROP"); //打开系统自带的裁剪图片的intent
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
/*
        // 注意一定要添加该项权限，否则会提示无法裁剪
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        intent.putExtra("scale", true);

        // 设置裁剪区域的宽高比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // 设置裁剪区域的宽度和高度
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
*/
        // 取消人脸识别
        intent.putExtra("noFaceDetection", true);
        // 图片输出格式
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        // 若为false则表示不返回数据
        intent.putExtra("return-data", false);

        // 指定裁剪完成以后的图片所保存的位置,pic info显示有延时
        if (fromCapture) {
            // 如果是使用拍照，那么原先的uri和最终目标的uri一致,注意这里的uri必须是Uri.fromFile生成的
            txUri = Uri.fromFile(imgFile);
        } else { // 从相册中选择，那么裁剪的图片保存在take_photo中
            String time = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
            String fileName = "photo_" + time;
            File mCutFile = new File(Environment.getExternalStorageDirectory() + "/take_photo/", fileName + ".jpeg");
            if (!mCutFile.getParentFile().exists()) {
                mCutFile.getParentFile().mkdirs();
            }
            txUri = Uri.fromFile(mCutFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, txUri);
        Toast.makeText(getActivity(), "剪裁图片", Toast.LENGTH_SHORT).show();
        // 以广播方式刷新系统相册，以便能够在相册中找到刚刚所拍摄和裁剪的照片
        Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intentBc.setData(uri);
        this.getActivity().sendBroadcast(intentBc);

        startActivityForResult(intent, REQUEST_CROP); //设置裁剪参数显示图片至ImageVie
    }
}
